package com.haifeng.lyw.blerobot.search;

import android.Manifest;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.RequiresApi;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;

import com.haifeng.lyw.blerobot.ActionActivity;
import com.haifeng.lyw.blerobot.R;
import com.haifeng.lyw.blerobot.utils.BleInfo;

import java.util.ArrayList;
import java.util.List;


/**
 * 特别说明：HC_BLE助手是广州汇承信息科技有限公司独自研发的手机APP，方便用户调试08蓝牙模块。
 * 本软件只能支持安卓版本4.3并且有蓝牙4.0的手机使用。
 * 另外对于自家的05、06模块，要使用另外一套蓝牙2.0的手机APP，用户可以在汇承官方网的下载中心自行下载。
 * 本软件提供代码和注释，免费给购买汇承08模块的用户学习和研究，但不能用于商业开发，最终解析权在广州汇承信息科技有限公司。
 **/

/**
 * @author 广州汇承信息科技有限公司
 * @Description: TODO<MainActivity类实现打开蓝牙、扫描蓝牙>
 * @data: 2014-10-12 上午10:28:18
 * @version: V1.0
 */
public class SearchActivity extends Activity implements OnClickListener, AdapterView.OnItemClickListener {
    // 扫描蓝牙按钮
    private Button scan_btn;
    // 蓝牙适配器
    BluetoothAdapter mBluetoothAdapter;
    // 蓝牙信号强度
    private ArrayList<Integer> rssis;
    // 自定义Adapter
    LeDeviceListAdapter mleDeviceListAdapter;
   // DeviceListAdapter deviceListAdapter;
    // listview显示扫描到的蓝牙信息
    ListView lv;
    // 描述扫描蓝牙的状态
    private boolean mScanning;
    private boolean scan_flag;
    private Handler mHandler;
    int REQUEST_ENABLE_BT = 1;
    // 蓝牙扫描时间
    private static final long SCAN_PERIOD = 10000;

    private SharedPreferences sp = null;

    private RadioGroup radioGroup;
    private RadioButton  radioPai;

    /**
     * true 为1控制页面
     * false为 排爆控制页面
     */
    // private boolean isSelectorFang = true;

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search);

        rssis = new ArrayList<>();
        // 初始化控件
        init();
        // 初始化蓝牙
        init_ble();
        scan_flag = true;

        List<DeviceBean> devices = new ArrayList<>();
        DeviceBean b = new DeviceBean();
        sp = getSharedPreferences("blue_tooth_device",Context.MODE_PRIVATE);
        b.setName(sp.getString("deviceName",""));
        b.setAddr(sp.getString("deviceAdd",""));
        b.setRssi(sp.getInt("rssi",0));
        devices.add(b);
        // 自定义适配器
       mleDeviceListAdapter = new LeDeviceListAdapter(this);
//        deviceListAdapter = new DeviceListAdapter(devices,this);
        // 为listview指定适配器
       lv.setAdapter(mleDeviceListAdapter);

//        lv.setAdapter(deviceListAdapter);


		/* listview点击函数 */
        lv.setOnItemClickListener(this);


        if (Build.VERSION.SDK_INT >= 23) {
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this, new String[]{
                        Manifest.permission.ACCESS_COARSE_LOCATION
                }, 10);
            }
        }
    }

    /**
     * @param
     * @return void
     * @throws
     * @Title: init
     * @Description: TODO(初始化UI控件)
     */
    private void init() {
        scan_btn = (Button) this.findViewById(R.id.scan_dev_btn);
        scan_btn.setOnClickListener(this);
        lv = (ListView) this.findViewById(R.id.lv);
        mHandler = new Handler();

        radioGroup = (RadioGroup) findViewById(R.id.radio_group);
        //  radioFang = (RadioButton) findViewById(R.id.radio_fang);
        radioPai = (RadioButton) findViewById(R.id.radio_pai);




    }

    /**
     * @param
     * @return void
     * @throws
     * @Title: init_ble
     * @Description: TODO(初始化蓝牙)
     */
    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
    private void init_ble() {
        // 手机硬件支持蓝牙
        if (!getPackageManager().hasSystemFeature(
                PackageManager.FEATURE_BLUETOOTH_LE)) {
            Toast.makeText(this, "不支持BLE", Toast.LENGTH_SHORT).show();
            finish();
        }
        // Initializes Bluetooth adapter.
        // 获取手机本地的蓝牙适配器
        final BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
        mBluetoothAdapter = bluetoothManager.getAdapter();
        // 打开蓝牙权限
        if (mBluetoothAdapter == null || !mBluetoothAdapter.isEnabled()) {
            Intent enableBtIntent = new Intent(
                    BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
        }

    }

    /*
     * 按钮响应事件
     */
    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub

        if (scan_flag) {
//            mleDeviceListAdapter = new LeDeviceListAdapter(this);
//            lv.setAdapter(mleDeviceListAdapter);
//            deviceListAdapter = new DeviceListAdapter(null,this);
//            lv.setAdapter(deviceListAdapter);
            scanLeDevice(true);
        } else {

            scanLeDevice(false);
            scan_btn.setText("开始扫描");
        }
    }

    /**
     * @param enable (扫描使能，true:扫描开始,false:扫描停止)
     * @return void
     * @throws
     * @Title: scanLeDevice
     * @Description: TODO(扫描蓝牙设备)
     */
    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
    private void scanLeDevice(final boolean enable) {
        if (enable) {
            // Stops scanning after a pre-defined scan period.
            mHandler.postDelayed(new Runnable() {
                @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
                @Override
                public void run() {
                    mScanning = false;
                    scan_flag = true;
                    scan_btn.setText("开始扫描");
                    Log.i("SCAN", "stop.....................");
                    mBluetoothAdapter.stopLeScan(mLeScanCallback);
                }
            }, SCAN_PERIOD);
            /* 开始扫描蓝牙设备，带mLeScanCallback 回调函数 */
            Log.i("SCAN", "begin.....................");
            mScanning = true;
            scan_flag = false;
            scan_btn.setText("正在搜索。。。");
            mBluetoothAdapter.startLeScan(mLeScanCallback);
        } else {
            Log.i("Stop", "stoping................");
            mScanning = false;
            mBluetoothAdapter.stopLeScan(mLeScanCallback);
            scan_flag = true;
        }

    }

    /**
     * 蓝牙扫描回调函数 实现扫描蓝牙设备，回调蓝牙BluetoothDevice，可以获取name MAC等信息
     **/
    private BluetoothAdapter.LeScanCallback mLeScanCallback = new BluetoothAdapter.LeScanCallback() {

        @Override
        public void onLeScan(final BluetoothDevice device, final int rssi,
                             byte[] scanRecord) {
            // TODO Auto-generated method stub

            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    /* 讲扫描到设备的信息输出到listview的适配器 */
                    rssis.add(rssi);
                    mleDeviceListAdapter.addDevice(device, rssi);
                    mleDeviceListAdapter.notifyDataSetChanged();
                    DeviceBean bean = new DeviceBean();
                    bean.setName(device.getName());
                    bean.setAddr(device.getAddress());
                    bean.setRssi(rssi);
     //               deviceListAdapter.addDevice(bean);

                }
            });

            System.out.println("Address:" + device.getAddress());
            System.out.println("Name:" + device.getName());
            System.out.println("rssi:" + rssi);

        }
    };


    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        final BluetoothDevice device = mleDeviceListAdapter.getDevice(position);
   //     final DeviceBean device = deviceListAdapter.getDevice(position);
        if (device == null)
            return;

        final Intent intent = new Intent();

//        if (isSelectorFang) {
//            intent.setClass(SearchActivity.this,
//                    MainActivity.class);
//        } else {
        intent.setClass(SearchActivity.this,
                ActionActivity.class);
        //    }
        intent.putExtra(BleInfo.EXTRAS_DEVICE_NAME,
                device.getName());
        intent.putExtra(BleInfo.EXTRAS_DEVICE_ADDRESS,
                device.getAddress());
//        intent.putExtra(BleInfo.EXTRAS_DEVICE_RSSI,
//                device.getRssi()+"");

        //把点击的item的信息存储到本地
        SharedPreferences.Editor editor = sp.edit();
        editor.putString("deviceName",device.getName());
        editor.putString("deviceAdd",device.getAddress());
//        editor.putInt("rssi",device.getRssi());
        editor.commit();

        if (mScanning) {
					/* 停止扫描设备 */
            mBluetoothAdapter.stopLeScan(mLeScanCallback);
            mScanning = false;
        }

        try {
            // 启动ActionActivity
            startActivity(intent);
        } catch (Exception e) {
            e.printStackTrace();
            // TODO: handle exception
        }
    }


}
